package com.mmall.controller.portal;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.google.common.collect.Maps;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IOrderService;
import net.guerlab.sdk.alipay.config.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by hanchao on 2018/1/24.
 */
@RestController
@RequestMapping(value = "/order/")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private AlipayConfig alipayConfig;


    @RequestMapping(value = "create.do")
    public ServerResponse create (HttpSession session,Integer shippingId){
        User user =(User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createdByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.createOrder(user.getId(),shippingId);
    }
    @RequestMapping(value = "cancel.do")
    public ServerResponse cancel (HttpSession session,Long orderNo){
        User user =(User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createdByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.cancel(user.getId(),orderNo);
    }
    //获取购物车选中的商品详情
    @RequestMapping(value = "get_order_cart_product.do")
    public ServerResponse getOrderCartProduct (HttpSession session,Long orderNo){
        User user =(User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createdByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderCartProduct(user.getId());
    }
    @RequestMapping(value = "detail.do")
    public ServerResponse detail (HttpSession session,Long orderNo){
        User user =(User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createdByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderDetail(user.getId(),orderNo);
    }
    @RequestMapping(value = "list.do")
    public ServerResponse list (HttpSession session, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        User user =(User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createdByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        return iOrderService.getOrderList(user.getId(),pageNum,pageSize);
    }
    /**
     * 预下单
     * @param session
     * @param orderNo
     * @param request
     * @return
     */
    @RequestMapping(value = "pay")
    public ServerResponse pay (HttpSession session, Long orderNo, HttpServletRequest request){
        User user =(User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createdByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        return iOrderService.pay(user.getId(),orderNo,path);
    }

    @RequestMapping(value = "alipay_callback.do")
    public Object alipayCallback(HttpServletRequest request){
        Map<String,String> params = Maps.newHashMap();

        Map requestParams  = request.getParameterMap();
        for(Iterator iter = requestParams.keySet().iterator();iter.hasNext(); ){
            String name = (String)iter.next();
            String[] value = (String[])requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i<value.length;i++){
                valueStr = (i == value.length-1)?valueStr+value[i]:valueStr+",";
            }
            params.put(name,valueStr);
        }
        logger.info("支付宝回调sign:{},trade_status:{},参数：{}",params.get("sign"),params.get("trade_status"),params.toString());
        //验证通知是否是支付宝发出的，并且避免重复通知
        params.remove("sign_type");

        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params,alipayConfig.getAlipayPublicKey(),"utf-8", AlipayConstants.SIGN_TYPE_RSA);
            if(!alipayRSACheckedV2){
                return ServerResponse.createdByErrorMessage("非法请求，验证不通过,再恶意请求就报警找网警了");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //TODO  验证各种数据
        ServerResponse serverResponse = iOrderService.aliCallback(params);
        if(serverResponse.isSuccess()){
            return Const.AlipayCallback.RESPONSE_SUCCESS;
        }
        return Const.AlipayCallback.RESPONSE_FAILED;
    }

    //检查是否付款成功（轮询）
    @RequestMapping(value = "query_order_pay_status")
    public ServerResponse<Boolean> queryOrderPayStatus (HttpSession session, Long orderNo, HttpServletRequest request){
        User user =(User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createdByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),ResponseCode.NEED_LOGIN.getDesc());
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        ServerResponse response = iOrderService.queryOrderPayStatus(user.getId(),orderNo);
        if (response.isSuccess()){
            return ServerResponse.createdBySuccess(true);
        }
        return ServerResponse.createdBySuccess(false);
    }





}
